import { defineStore } from "pinia";
import Taro from "@tarojs/taro";

export const useUserStore = defineStore("user", {
  state: () => ({
    userInfo: {
      avatar:
        "https://img12.360buyimg.com/imagetools/jfs/t1/196430/38/8105/14329/60c806a4Ed506298a/e6de9fb7b8490f38.png",
      nickname: "用户昵称",
      gender: "male",
      birthday: "",
      region: [],
      phone: "",
      email: "",
    },
    isLoggedIn: false,
  }),

  getters: {
    // 获取用户信息
    getUserInfo: (state) => state.userInfo,
    // 获取登录状态
    getLoginStatus: (state) => state.isLoggedIn,
  },

  actions: {
    // 更新用户信息
    updateUserInfo(info) {
      this.userInfo = { ...this.userInfo, ...info };
      this.saveToStorage();
    },

    // 更新单个字段
    updateUserField(field, value) {
      this.userInfo[field] = value;
      this.saveToStorage();
    },

    // 保存到本地存储
    saveToStorage() {
      Taro.setStorageSync("userInfo", this.userInfo);
    },

    // 从本地存储加载
    loadFromStorage() {
      const userInfo = Taro.getStorageSync("userInfo");
      if (userInfo) {
        this.userInfo = userInfo;
        this.isLoggedIn = true;
      }
    },

    // 清除用户信息
    clearUserInfo() {
      this.userInfo = {
        avatar:
          "https://img12.360buyimg.com/imagetools/jfs/t1/196430/38/8105/14329/60c806a4Ed506298a/e6de9fb7b8490f38.png",
        nickname: "用户昵称",
        gender: "male",
        birthday: "",
        region: [],
        phone: "",
        email: "",
      };
      this.isLoggedIn = false;
      Taro.removeStorageSync("userInfo");
    },

    // 设置登录状态
    setLoginStatus(status) {
      this.isLoggedIn = status;
    },
  },
});
